package pl.edu.mimuw.mas.editor.listener;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.chart.Chart;
import pl.edu.mimuw.mas.editor.MainEditorWindow;
import pl.edu.mimuw.mas.utils.Marshaller;

/**
 * Implementacja Listenera dla przycisku "open" w menu
 * głównym aplikacji.
 */
public class OpenMenuItemListener implements SelectionListener {
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	private final FileDialog fd;
	private final MainEditorWindow main;
	private final String pathFilter = "/";
	private final String[] filterExt = { "*.map", "*.*" };

	
	public OpenMenuItemListener(Shell shell, MainEditorWindow main) {
		fd = new FileDialog(shell, SWT.OPEN);
		fd.setText("Open");
		fd.setFilterPath(pathFilter);
		fd.setFilterExtensions(filterExt);
		this.main = main;
	}
	
	public void widgetSelected(SelectionEvent event) {
		log.debug("Wybrano");
		log.debug("Otwieram okno dialogowe");
		String selected = fd.open();
		if (selected != null) {
			log.info("Okno zamknięte z plikiem \"" + selected + "\"");
			openFile(selected);
			log.debug("Włączam zapisywanie");
			main.enableSaving();
			log.debug("Włączam zapisywanie jako");
			main.enableSavingAs();
		} else {
			log.info("Okno zamknięte bez wybranego pliku");
		}
	}

	public void widgetDefaultSelected(SelectionEvent event) {
	}
	
	public void openFile(String fileName) {
		main.setFileName(fileName);
		main.setChart((Chart) Marshaller.read(fileName));
		log.info("Plik " + fileName + " otwarty");
	}
}
